package api

import (
	"net/http"

	"example.com/rest/example/dao"
	"example.com/rest/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configArtistsRouter(router *httprouter.Router) {
	router.GET("/artists", GetAllArtists)
	router.POST("/artists", AddArtists)
	router.GET("/artists/:argArtistID", GetArtists)
	router.PUT("/artists/:argArtistID", UpdateArtists)
	router.DELETE("/artists/:argArtistID", DeleteArtists)
}

func configGinArtistsRouter(router gin.IRoutes) {
	router.GET("/artists", ConverHttprouterToGin(GetAllArtists))
	router.POST("/artists", ConverHttprouterToGin(AddArtists))
	router.GET("/artists/:argArtistID", ConverHttprouterToGin(GetArtists))
	router.PUT("/artists/:argArtistID", ConverHttprouterToGin(UpdateArtists))
	router.DELETE("/artists/:argArtistID", ConverHttprouterToGin(DeleteArtists))
}

// GetAllArtists is a function to get a slice of record(s) from artists table in the main database
// @Summary Get list of Artists
// @Tags Artists
// @Description GetAllArtists is a handler to get a slice of record(s) from artists table in the main database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.Artists}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /artists [get]
// http "http://localhost:8080/artists?page=0&pagesize=20" X-Api-User:user123
func GetAllArtists(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "artists", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllArtists(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetArtists is a function to get a single record from the artists table in the main database
// @Summary Get record from table Artists by  argArtistID
// @Tags Artists
// @ID argArtistID
// @Description GetArtists is a function to get a single record from the artists table in the main database
// @Accept  json
// @Produce  json
// @Param  argArtistID path int true "ArtistId"
// @Success 200 {object} model.Artists
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /artists/{argArtistID} [get]
// http "http://localhost:8080/artists/1" X-Api-User:user123
func GetArtists(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argArtistID, err := parseInt32(ps, "argArtistID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "artists", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetArtists(ctx, argArtistID)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddArtists add to add a single record to artists table in the main database
// @Summary Add an record to artists table
// @Description add to add a single record to artists table in the main database
// @Tags Artists
// @Accept  json
// @Produce  json
// @Param Artists body model.Artists true "Add Artists"
// @Success 200 {object} model.Artists
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /artists [post]
// echo '{"artist_id": 17,"name": "etxvDJbeSXfytgPjERJcXcOYq"}' | http POST "http://localhost:8080/artists" X-Api-User:user123
func AddArtists(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	artists := &model.Artists{}

	if err := readJSON(r, artists); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := artists.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	artists.Prepare()

	if err := artists.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "artists", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	artists, _, err = dao.AddArtists(ctx, artists)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, artists)
}

// UpdateArtists Update a single record from artists table in the main database
// @Summary Update an record in table artists
// @Description Update a single record from artists table in the main database
// @Tags Artists
// @Accept  json
// @Produce  json
// @Param  argArtistID path int true "ArtistId"
// @Param  Artists body model.Artists true "Update Artists record"
// @Success 200 {object} model.Artists
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /artists/{argArtistID} [put]
// echo '{"artist_id": 17,"name": "etxvDJbeSXfytgPjERJcXcOYq"}' | http PUT "http://localhost:8080/artists/1"  X-Api-User:user123
func UpdateArtists(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argArtistID, err := parseInt32(ps, "argArtistID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	artists := &model.Artists{}
	if err := readJSON(r, artists); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := artists.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	artists.Prepare()

	if err := artists.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "artists", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	artists, _, err = dao.UpdateArtists(ctx,
		argArtistID,
		artists)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, artists)
}

// DeleteArtists Delete a single record from artists table in the main database
// @Summary Delete a record from artists
// @Description Delete a single record from artists table in the main database
// @Tags Artists
// @Accept  json
// @Produce  json
// @Param  argArtistID path int true "ArtistId"
// @Success 204 {object} model.Artists
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /artists/{argArtistID} [delete]
// http DELETE "http://localhost:8080/artists/1" X-Api-User:user123
func DeleteArtists(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argArtistID, err := parseInt32(ps, "argArtistID")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "artists", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeleteArtists(ctx, argArtistID)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
